<template>
	<view class="page-body">
		<!-- 页面内容开始 -->

		<!-- 表格搜索组件开始 -->
		<vk-data-table-query
			v-model="queryForm1.formData"
			:columns="queryForm1.columns"
			size="mini"
			@search="search"
		>
			<template slot="right-btns">
				<el-button type="success" icon="el-icon-circle-plus-outline" @click="addBtn">
					添加
				</el-button>
			</template>
		</vk-data-table-query>
		<!-- 表格搜索组件结束 -->

		<!-- 表格组件开始 	:detail-dialog-width="1200" -->
		<vk-data-table
			ref="table1"
			:action="table1.action"
			:columns="table1.columns"
			:query-form-param="queryForm1"
			:right-btns="['detail_auto', 'update', 'delete']"
			:row-no="true"
			:pagination="true"
			size="mini"
			@update="updateBtn"
			@delete="deleteBtn"
			@current-change="currentChange"
			@selection-change="selectionChange"
		></vk-data-table>
		<!-- 表格组件结束 -->

		<!-- 添加或编辑的弹窗开始 -->
		<vk-data-drawer v-model="formData1.show" :title="formData1.title" center width="1000px">
			<vk-data-form
				v-model="form1"
				:rules="formData1.rules"
				:action="formData1.action"
				:form-type="formData1.formType"
				:columns="formData1.columns"
				label-width="120px"
				:submit-disabled="submit_disabled"
				style="padding: 20px;"
				@success="formSuccess"
			>
				<template slot="freight_rules" slot-scope="{ form, keyName, val }">
					<el-button type="primary" size="mini" @click="select_province">添加可配送区域</el-button>
					<el-table :data="val" fit border class="" size="small" style="margin-top: 10px;">
						<el-table-column label="可配送区域" min-width="240">
							<template slot-scope="scope">
								<text>{{ scope.row.province_names.join("、") }}</text>
							</template>
						</el-table-column>
						<el-table-column label="首重（KG）" width="140" align="center">
							<template slot-scope="scope">
								<vk-data-input-number v-model="scope.row.first_weight" :precision="0"  placeholder="请输入首重" size="small"></vk-data-input-number>
							</template>
						</el-table-column>
						<el-table-column label="运费（元）" width="140" align="center">
							<template slot-scope="scope">
								<vk-data-input-money v-model="scope.row.first_weight_price" placeholder="请输入运费" size="small"></vk-data-input-money>
							</template>
						</el-table-column>
						<el-table-column label="续重（KG）" width="140" align="center">
							<template slot-scope="scope">
								<vk-data-input-number v-model="scope.row.continuous_weight" :precision="0"  placeholder="请输入续重" size="small"></vk-data-input-number>
							</template>
						</el-table-column>
						<el-table-column label="续费（元）" width="135" align="center">
							<template slot-scope="scope">
								<vk-data-input-money v-model="scope.row.continuous_weight_price" placeholder="请输入续费" size="small"></vk-data-input-money>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="120" align="center">
							<template slot-scope="scope">
								<view style="display: flex;justify-content: center;">
									<el-link :underline="false" type="primary" @click="updateProvinceBtn(scope.row, scope.$index)" > 修改 </el-link>
									<el-link :underline="false" type="danger" @click="deleteProvinceBtn(scope.$index)" style="margin-left: 20px;" > 删除 </el-link>
								</view>
							</template>
						</el-table-column>
					</el-table>
				</template>
			</vk-data-form>
		</vk-data-drawer>
		<!-- 添加或编辑的弹窗结束 -->

		<vk-data-dialog
			v-model="formData2.show"
			title="省份选择"
			center
			@close="
				checkProvinceList = [];
				updateProvinceBtn_flag = false;
			"
		>
			<view class="checkbox">
				<el-checkbox-group v-model="checkProvinceList">
					<el-checkbox
						v-for="(value, index) in province"
						:key="index"
						:label="value.code"
						:disabled="value.code | disabled_list"
					>
						{{ value.name }}
					</el-checkbox>
				</el-checkbox-group>
			</view>
			<span slot="footer" class="dialog-footer">
				<el-button
					type="primary"
					:disabled="!checkProvinceList.length"
					@click="selectProvinceSubmit"
				>
					确定
				</el-button>
			</span>
		</vk-data-dialog>
		<!-- 页面内容结束 -->
	</view>
</template>

<script>
var that; // 当前页面对象
var vk = uni.vk; // vk实例
var originalForms = {}; // 表单初始化数据
var province = vk.addressUtil.getProvinces();
export default {
	data() {
		// 页面数据变量
		return {
			province,
			checkProvinceList: [],
			tableData: [],
			choice: true,
			updateProvinceBtn_index: 0, //更新的列表
			updateProvinceBtn_flag: false, //是否点击了更新
			updateProvinceBtn_arr: [],
			// 页面是否请求中或加载中
			loading: false,
			// init请求返回的数据
			data: {},
			// 表格相关开始 -----------------------------------------------------------
			table1: {
				// 表格数据请求地址
				action: "admin/business/sys/freight.getList",
				// 表格字段显示规则
				columns: [
					//{ key: "_id", title: "运费模板ID", type: "text", minWidth: 200 },
					{ key: "name", title: "运费模板名称", type: "text", minWidth: 200 },
					{ key: "max_weight", title: "拆包重量", type: "number", width: 100, defaultValue: "不拆包" },
					{ key: "comment", title: "备注", type: "text", minWidth: 200 },
					{ key: "is_default", title:"是否默认", type:"switch", activeValue:true, inactiveValue:false },
					{
						key: "freight_rules",
						title: "运费规则",
						type: "table",
						minWidth: 200,
						show: ["detail"],
						maxHeight: 600,
						columns: [
							{ key: "province_names", title: "省列表", type: "text", minWidth: 200, align: "left" },
							{ key: "first_weight", title: "首重（KG）", type: "text", width: 80 },
							{ key: "first_weight_price", title: "首重价格（元）", type: "money", width: 80 },
							{ key: "continuous_weight", title: "续重（KG）", type: "text", width: 80 },
							{ key: "continuous_weight_price", title: "续重价格（元）", type: "money", width: 80 }
						]
					}
				],
				// 多选框选中的值
				multipleSelection: [],
				// 当前高亮的记录
				selectItem: ""
			},
			// 表格相关结束 -----------------------------------------------------------
			// 表单相关开始 -----------------------------------------------------------
			// 查询表单请求数据
			queryForm1: {
				// 查询表单数据源，可在此设置默认值
				formData: {},
				// 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
				columns: [
					{ key: "name", title: "运费模板名称", type: "text", mode: "%%" },
				]
			},
			// 表单数据源，可在此设置默认值
			// 表单数据源，可在此设置默认值
			form1: {
				max_weight: "",
				comment: "",
				freight_rules: []
			},
			formData1: {
				// 表单请求地址
				action: "",
				// 表单字段显示规则
				columns: [
					{ key: "name", title: "运费模板名称", type: "text" },
					{ key: "max_weight",title: "拆包重量",type: "number",placeholder: "请输入拆包重量（KG）", tips:"如拆包重量为5KG，订单包裹重量5.1KG，则要付2次首重的费用（相当于发2个包裹）。若订单包裹重量10.1KG，则要付3次首重的费用（相当于发3个包裹），填0或不填则1个订单只计算1次首重费用。" },
					{ key: "comment",title: "运费模板备注",type: "text",placeholder: "请输入运费模板备注" },
					{ key: "freight_rules", title: "", type: "text", data: province, showLabel:false },
					{ key: "is_default", title:"是否默认", type:"switch", activeValue:true, inactiveValue:false, tips:"是否设为默认运费模板"  }
				],
				// 表单验证规则
				rules: {
					name: [
						{ required: true, message: "该项必填", trigger: ['blur','change'] }
					],
				},
				// add 代表添加 update 代表修改
				formType: "",
				// 是否显示表单的弹窗
				show: false
			},
			formData2: {
				columns: [
					{
						key: "max_weight",
						title: "拆包重量",
						type: "number",
						placeholder: "请输入拆包重量（KG）"
					}
				],
				show: false
			},

			// 表单相关结束 -----------------------------------------------------------
		};
	},
	// 监听 - 页面每次【加载时】执行(如：前进)
	onLoad(options = {}) {
		that = this;
		vk = that.vk;
		that.options = options;
		that.init(options);
	},
	// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
	onReady() {},
	// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
	onShow() {},
	// 监听 - 页面每次【隐藏时】执行(如：返回)
	onHide() {},
	// 函数
	methods: {
		// 页面数据初始化函数
		init(options) {
			originalForms["form1"] = vk.pubfn.copyObject(that.form1);
		},
		// 页面跳转
		pageTo(path) {
			vk.navigateTo(path);
		},
		// 表单重置
		resetForm() {
			vk.pubfn.resetForm(originalForms, that);
		},
		// 搜索
		search() {
			that.$refs.table1.query();
		},
		// 刷新
		refresh() {
			that.$refs.table1.refresh();
		},
		// 获取当前选中的行的数据
		getCurrentRow() {
			return that.$refs.table1.getCurrentRow();
		},
		// 监听 - 行的选中高亮事件
		currentChange(val) {
			that.table1.selectItem = val;
		},
		// 当选择项发生变化时会触发该事件
		selectionChange(list) {
			that.table1.multipleSelection = list;
		},
		// 显示添加页面
		addBtn() {
			that.resetForm();
			that.formData1.action = "admin/business/sys/freight.addUpdate";
			that.formData1.formType = "add";
			that.formData1.title = "添加";
			that.formData1.show = true;
		},
		// 显示修改页面
		updateBtn({ item }) {
			that.formData1.action = "admin/business/sys/freight.addUpdate";
			that.formData1.formType = "update";
			that.formData1.title = "编辑";
			that.formData1.show = true;
			that.form1 = item;
		},
		// 删除按钮
		deleteBtn({ item, deleteFn }) {
			deleteFn({
				action: "admin/business/sys/freight.delete",
				data: {
					_id: item._id
				}
			});
		},
		// 打开选择省份的弹窗
		select_province() {
			that.formData2.show = true;
		},
		// 选择省份的弹窗点击确认按钮
		selectProvinceSubmit() {
			let { checkProvinceList } = that;
			let province_codes = checkProvinceList;
			let province_names = [];
			for (let i in province_codes) {
				let item = vk.pubfn.getListItem(province, "code", province_codes[i]);
				province_names.push(item.name);
			}
			// 判断是否点击了修改按钮
			if (this.updateProvinceBtn_flag) {
				//若是修改状态，则只改变当条数据的省列表和省id列表并将修改按钮开关关闭
				let item = that.form1.freight_rules[this.updateProvinceBtn_index];
				item.province_codes = province_codes;
				item.province_names = province_names;
				// 将修改按钮开关关闭
				this.updateProvinceBtn_flag = false;
			} else {
				if (province_codes.length) {
					//当选着有数据时才能够添加
					// 添加一条新的列表数据
					that.form1.freight_rules.push({
						province_codes,
						province_names,
						first_weight: 1,
						first_weight_price: "",
						continuous_weight: 1,
						continuous_weight_price: ""
					});
				}
			}
			that.checkProvinceList = [];
			that.formData2.show = false;
		},
		// 修改按钮
		updateProvinceBtn(item, index) {
			// 打开修改开关
			this.updateProvinceBtn_flag = true;
			// 修改的当前数据index
			this.updateProvinceBtn_index = index;
			that.checkProvinceList = item.province_codes;
			that.formData2.show = true;
		},
		// 删除按钮
		deleteProvinceBtn(index) {
			that.form1.freight_rules.splice(index, 1);
		},
		// 点击确定按钮提交成功后关闭弹窗
		formSuccess() {
			// 关闭弹窗
			that.formData1.show = false;
			// 刷新界面
			that.refresh();
		}
	},
	watch: {},
	// 过滤器
	filters: {
		disabled_list(code) {
			// 获取到所有的列表数据
			let freight_rules = that.form1.freight_rules;
			// 获取到是否处于修改状态
			let flag = that.updateProvinceBtn_flag;
			// 获取到要修改的当前行的行号
			let index = that.updateProvinceBtn_index;
			// 分析:
			// 1选择省份时，只需要把所有列表数据对应code的checked禁用
			// 2修改时，除了当前行的所有列表数据的cdoe给禁用。
			// 3若所有列表数据为空时，则不做任何处理，直接返回false(不禁用)
			if (freight_rules.length) {
				//列表数据为空时，则不做任何处理(刚开始时)
				let code_list = []; //code列表
				if (flag) {
					//修改状态
					// 获取除了当前修改行所有code数据
					for (let [key, value] of freight_rules.entries()) {
						if (key != index) {
							//index(当前修改所在的行号)，
							code_list = code_list.concat(value.province_codes);
						}
					}
				} else {
					//不修改状态 。当传入进来的code是否在code_list(已经选中过的了)里面，若在返回true(禁用)，反之亦然。
					// 获取到所有的列表数据的code
					for (let [key, value] of freight_rules.entries()) {
						code_list = code_list.concat(value.province_codes);
					}
				}
				return code_list.includes(code);
			} else {
				return false;
			}
		}
	},
	// 计算属性
	computed: {
		checkedProvinceCom() {
			let freight_rules = that.form1.freight_rules;
			let arr = [];
			for (let i in freight_rules) {
				arr = arr.concat(freight_rules[i].province_codes);
			}
			return arr;
		},
		submit_disabled() {
			//添加的按钮是否禁用
			let freight = that.form1.freight_rules;
			// 没有可配送区域时，禁用按钮
			// 运费和续费不填时(不等于空)，禁用按钮
			if (!freight.length) return true;
			return freight.some((value, index, arr) => {
				return !vk.pubfn.isNotNullAll(value.first_weight_price, value.continuous_weight_price)
			});
		}
	}
};
</script>
<style lang="scss" scoped>
// 主体部分
.checkbox {
	.el-checkbox {
		width: 20%;
		margin-top: 15px;
	}
	.el-button {
		margin-left: auto;
	}
}
::v-deep .el-dialog {
	display: flex;
	flex-direction: column;
}
::v-deep .el-dialog__body {
	flex: 1;
	display: flex;
	flex-direction: column;
}
.el-header {
	display: flex;
	justify-content: center;
	align-items: center;
	::v-deep .header_input {
		flex: 0.4;
		&:first-of-type {
			margin-right: 50px;
		}
	}
}

</style>
